package com.lj.frame.config.auth;


import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class AuthConfig implements WebMvcConfigurer {

    private final AuthenticationInterceptor authenticationInterceptor;
    private final DecryptFilter decryptFilter;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor)
                .excludePathPatterns("/user/login",   "/**/p_*", "/**/p_*/**", "**/error", "/code**")
                //订单 notifyResult
                .excludePathPatterns("/orders/create", "/orders/query",  "/orders/refund", "/orders/cancel", "/orders/close",  "/orders/queryRefund", "/orders/notify-result**")
                // swagger2原生UI需要swagger-ui  knife-ui需要doc.html
                .excludePathPatterns("/swagger-ui/**")//原生swagger-ui
                .excludePathPatterns("/doc.html**") //knife4
                .excludePathPatterns("/webjars/**", "/v2/api-docs**","/swagger-resources", "/swagger-resources/**")
                .addPathPatterns("/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //cookie
                .allowCredentials(true)
                //请求方式
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")//允许的信息头
                .exposedHeaders("*")//暴露的信息头
                //.allowedOrigins("*");
                .allowedOriginPatterns("*");
    }

    /**
     * 注入解密过滤器
     * */
    @Bean
    public FilterRegistrationBean servletRegistrationBean(){
        FilterRegistrationBean<DecryptFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(decryptFilter);
        bean.setName("DecryptFilter");
        bean.addUrlPatterns("/*");
        bean.setOrder(Ordered.LOWEST_PRECEDENCE);

        return bean;
    }


}
